<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../../admin/css/reset.css"/>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
</head>

<body>
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item">
                <label class="layui-form-label">账号</label>
                <div class="layui-input-block">
                    <input type="text" id="account" maxlength="16" name="account" lay-verify="required"
                           placeholder="账号" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" id="real_name" maxlength="16" name="real_name" lay-verify="required"
                           placeholder="姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="text" id="password" maxlength="16" name="password" lay-verify="required"
                           placeholder="请输入密码" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label for="" class="layui-form-label">角色</label>
                <div id="roleGroup" class="layui-input-block">
                    <div id="roleView"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit="" lay-filter="user-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>


<!-- LayUI模板 角色选择显示 -->
<script id="roleTempl" type="text/html">
    {{#  layui.each(d.list, function(index, item){ }}
    <input type="checkbox" name='roles' value={{ item.value }} title={{ item.title }}
           {{ item.checked ? 'checked' : '' }}>
    {{#  }); }}
    {{#  if(d.list.length === 0){ }}
    没有权限
    {{#  } }}
</script>


<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script src="../../../lms/base64.js"></script>
<script src="../../../lms/common.js"></script>
<script src="../../../lms/config.js"></script>
<script>

    const PRIMARY_KEY = "id";
    const SELECT_API = lms_config.api_url + "/api/setting/user/select";
    const DETAIL_API = lms_config.api_url + "/api/setting/user/get";
    const INSERT_API = lms_config.api_url + "/api/setting/user/insert";
    const UPDATE_API = lms_config.api_url + "/api/setting/user/update";
    const SELECT_ROLE_API = lms_config.api_url + "/api/setting/role/select";

    if (!checkLogin()) {
        location.href = lms_config.base_path + "/login.html";
    }


    layui.use(['form', 'jquery', 'laytpl', 'http', 'encrypt'], function () {
        let form = layui.form;
        let encrypt = layui.encrypt;
        let $ = layui.jquery;

        const laytpl = layui.laytpl;
        const http = layui.http;


        let method = 'POST';
        if (getQueryString('operation') === 'edit') {
            method = 'PUT';
        }


        //监听事件
        form.on('submit(user-save)', function (data) {

            if ($("[name=roles]:checked").length < 1) {
                ///$(data.elem).next().attr("class", "layui-unselect layui-form-checkbox");
                ///$(data.elem).prop("checked", false);
                layer.msg('请至少选择一个角色！', {icon: 5});
                return false;
            }

            //手动获取roles（因为checkbox默认只能获取最后一个的值）
            data.field.roles = [];

            //checked表示选择 状态为选择 的组件
            $('[name=roles]:checked').each(function (i, item) {    //选择器后遍历
                if ($(item).prop('checked'))
                    data.field.roles.push($(item).attr('value'));
            });
            data.field.roles = data.field.roles.join(',');


            if (data.field.password)
                data.field.password = encrypt.md5(data.field.password);
            else
                delete data.field.password;


            if (method === 'PUT') {
                data.field[PRIMARY_KEY] = getQueryString(PRIMARY_KEY)
            }

            $.ajax({
                url: method === 'POST' ? INSERT_API : UPDATE_API,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                dataType: 'json',
                success: function (ret) {
                    if (ret && ret.code == 0) {
                        layer.msg(ret.msg, {
                            icon: 1,
                            time: 1000
                        }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name)); //关闭当前页
                            parent.refresh();
                        });
                        return false;
                    } else {
                        layer.msg(ret.msg, {
                            icon: 2,
                            time: 1000
                        });
                        return false;
                    }
                },
                error: function (ret) {
                    console.error(ret);
                    alert("出错" + ret.status + "：" + ret.responseText);
                }, //表示如果请求响应出现错误，会执行的回调函数
            });

            return false;
        });


        //获取用户信息并渲染
        function getUser(roleData) {
            $.ajax({
                url: DETAIL_API + '/' + getQueryString(PRIMARY_KEY), // 请求路径
                type: "GET", //请求方式
                contentType: 'application/json',
                dataType: 'json',
                success: function (ret) {
                    if (ret.code !== 0) {
                        layer.msg(ret.msg, {
                            icon: 2,
                            time: 1000
                        }, function () {
                        });
                        return;
                    }

                    let user = ret.data;
                    let roleIds = user.roles.split(','); //role数组
                    for (let r of roleIds) { //遍历，将属于的用户组标记checked
                        if (roleData.obj[r]) roleData.obj[r].checked = true;
                    }
                    laytpl(roleTempl.innerHTML).render({
                        list: roleData.arr
                    }, function (html) {
                        document.getElementById('roleView').innerHTML = html;
                    });

                    $('#account').attr("value", user.account);
                    $('#account').prop("disabled", "true");
                    $('#real_name').attr("value", user.real_name);
                    $('#password').attr("lay-verify", "");
                    $('#password').attr("placeholder", "不修改则留空");

                    form.render();

                }, //响应成功后的回调函数
                error: function (ret) {
                    console.error(ret);
                    alert("出错" + ret.status + "：" + ret.responseText);
                }, //表示如果请求响应出现错误，会执行的回调函数
            });

        }


        /// 访问接口：角色
        $.ajax({
            url: SELECT_ROLE_API, // 请求路径
            type: "GET", //请求方式
            contentType: 'application/json',
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            dataType: "json",//设置接受到的响应数据的格式
            success: function (ret) {
                if (ret.code !== 0) {
                    layer.msg(ret.msg, {
                        icon: 2,
                        time: 1000
                    }, function () {
                    });
                    return;
                }

                //arr是数组用来显示，obj为了方便索引来checked
                let roleData = {
                    arr: [],
                    obj: {}
                };
                for (let d of ret.data) {
                    let r = {
                        title: d.role_name,
                        value: d.id
                    };
                    roleData.arr.push(r);
                    roleData.obj[d.id] = r;
                }

                //如果是编辑
                if (getQueryString('operation') === 'edit') {
                    getUser(roleData);

                } else
                    laytpl(roleTempl.innerHTML).render({
                        list: roleData.arr
                    }, function (html) {
                        document.getElementById('roleView').innerHTML = html;
                        form.render();
                    });

            }, //响应成功后的回调函数
            error: function (ret) {
                alert("出错" + ret.status + "：" + ret.responseText);
            }, //表示如果请求响应出现错误，会执行的回调函数

        });
    })
</script>
</body>

</html>
